import axios from 'axios'
import {
    Message,
    Notification
} from 'element-ui';
import { getToken, setToken, removeToken, setRefreshToken } from '@/utils/auth'
import router from '@/router'
// 优化错误提示只显示一个
function errorLog(message) {
    Notification.closeAll();
    if (!message) {
        return;
    }
    Notification({
        message: message,
        type: 'error',
        duration: 5000
    })
}
// 创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 3600000 // 请求超时时间
})
// let flag = true // 无痛请求 开关
// request拦截器
service.interceptors.request.use(
    config => {
        //  csiit token
        // config.headers['Authorization'] = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiJmNWQ5NWUwZjRlZDQ0NWI2Yjg3ODliNzlhZmNhYmI3NSIsImF1dGgiOiJhZG1pbiIsInN1YiI6ImNzaWl0In0.tirVmGDiLcD6jB3JffkMy4g_pcAzW2Jm-08JBRaVRVcBSHMztubWThsaT8kmOMiSIgI4UI4B6TEN3bVLgbQGYw'
        // 1的token
        // config.headers['Authorization'] = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiJjODcxNGVhM2U4NTQ0ZWYyOTQ5MTk4MWE4MjY1ZWI3MiIsImF1dGgiOiJ1c2VyOmxpc3QsdXNlcjphZGQscHVibGlzaDphbGFybUluZm8sbHYzLG1lbnU6bGlzdCxsdjQscm9sZXM6bGlzdCx1c2VyOmRlbCxkZXB0Omxpc3Qsam9iOmxpc3QsdXNlcjplZGl0LHJvbGVzOmVkaXQsZGljdDpsaXN0LHB1Ymxpc2g6YXZvaWREaXNhc3RlciIsInN1YiI6IjEifQ.9Kgws25OnOLDPTyH_s0xqKh5eeuWpFUHKEDgfja8RU8o6Pb5VxGt8N6_-TcrRenZQb_uss_MQxnG2aHvLbA3lw'
        config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        if (config.headers['Content-Type'] !== 'application/x-www-form-urlencoded') {
            config.headers['Content-Type'] = 'application/json'
        }
        // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        return config
    },
    error => {
        Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
        const { status } = response
        switch (status) {
            case 200:
                return response.data
            case 400:
                errorLog('status 400 错误信息请查看控制台')

                console.log(response.data.message)
                break
            case 401:
                errorLog('token 已过期')
                Notification.error({
                    title: 'token 已过期',
                    duration: 5000
                })
                removeToken()
                router.push('/login')
                break
            case 404:
                errorLog('404请求接口不存在')
                Notification.error({
                    title: '请求接口不存在',
                    duration: 5000
                })
                if (getRefreshToken()) {
                    try {
                        if (flag) {
                            flag = false
                            axios({
                                method: 'get',
                                baseURL: process.env.VUE_APP_BASE_API +
                                    'auth/token/refresh?refreshToken=' +
                                    getRefreshToken() + '&token=' + getToken(),
                                timeout: 6000 // 请求超时时间

                            }).then(res => {
                                const { code } = res.data
                                switch (code) {
                                    case 200:
                                        setToken(res.data.data.token)
                                        setRefreshToken(res.data.data.refreshToken)
                                        flag = true
                                        location.reload() // 刷新页面
                                        break
                                    case 400:
                                        Notification.error({
                                            title: 'token 已过期',
                                            duration: 5000
                                        })
                                        removeToken()
                                        router.push('/login')
                                }
                            }).catch(() => {
                                flag = true
                            })
                        }

                        // 如果获取成功，则把新的 token 更新到容器中
                    } catch (err) {
                        // 如果获取失败，直接跳转 登录页
                        console.log('请求刷线 token 失败', err)
                        router.push('/login')
                    }
                } else {
                    Notification.error({
                        title: 'token 已过期',
                        duration: 5000
                    })
                    removeToken()
                    router.push('/login')
                }
        }
    },
    error => {
        console.log('error', error)
        // 兼容blob下载出错json提示
        if (error.response && error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
            const reader = new FileReader()
            reader.readAsText(error.response.data, 'utf-8')
            reader.onload = function (e) {
                const errorMsg = JSON.parse(reader.result).message
                errorLog(errorMsg)
            }
        } else {
            let code = 0
            try {
                code = error.response.status
            } catch (e) {
                if (error.toString().indexOf('Error: timeout') !== -1) {
                    errorLog('网络请求超时')

                    return Promise.reject(error)
                }
            }
            console.log('error', code)
            if (code) {
                if (code === 401) {
                    console.log('401')
                    removeToken()
                    router.push('/login')
                    Notification.error({
                        title: 'token 已过期',
                        duration: 5000
                    })
                } else if (code === 403) {
                    console.log('403')
                } else if (code === 400) {
                    errorLog(error.response.data.message)

                    console.log(error.response.data.message)
                } else if (code === 500) {
                    console.log('500')
                    Message({
                        showClose: true,
                        message: '网络异常500',
                        type: 'error',
                        duration: 5 * 1000
                    });

                }
            }
        }
        return Promise.reject(error)
    }
)
export default service
